Skip to main content
ICT
Lesson A20 - Inheritance, Polymorphism, and Abstract Classes
 
Main Previous Next
Lesson A1 >  
Lesson A2 >  
Lesson A3 >  
Lesson A4 >  
Lesson A5 >  
Lesson A6 >  
Lesson A7 >  
Lesson A8 >  
Lesson A9 >  
Lesson A10 >  
Lesson A11 >  
Lesson A12 >  
Lesson A13 >  
Lesson A14 >  
Lesson A15 >  
Lesson A16 >  
Lesson A17 >  
Lesson A18 >  
Lesson A19 >  
Lesson A20 >  
Lesson A21 >  
Lesson A22 >  
Lesson AB23 >  
Lesson AB24 >  
Lesson AB25 >  
Lesson AB26 >  
Lesson AB27 >  
Lesson AB28 >  
Lesson AB29 >  
Lesson AB30 >  
Lesson AB31 >  
Lesson AB32 >  
Lesson AB33 >  
 

B. Abstract Classes page 4 of 8

  1. The classes that lie closer to the top of the hierarchy are more general and abstract; the classes closer to the bottom are more specialized. Java allows us to formally define an abstract class. In an abstract class, some or all methods are declared abstract and left without code.

  2. An abstract method has only a heading: a declaration that gives the method’s name, return type, and arguments. An abstract method has no code. For example, all of the methods in the definition of the SeaCreature class shown below are abstract. SeaCreature tells us what methods a sea creature must have, but not how they work.

    // A type of creature in the sea
    public abstract class SeaCreature{
      // Called to move the creature in its environment
      public abstract void swim();

      // Attempts to breed into neighboring locations
      public abstract void breed();

      // Removes this creature from the environment
      public abstract void die();

      // Returns the name of the creature
      public abstract String getName();
    }

  3. In an abstract class, some methods and constructors may be fully defined and have code supplied for them while other methods are abstract. A class may be declared abstract for other reasons as well. For example, some of the instance variables in an abstract class may belong to abstract classes.

  4. More specialized subclasses of an abstract class have more and more methods defined. Eventually, down the inheritance line, the code is supplied for all methods. A class where all the methods are fully defined is called a concrete class. A program can only create objects of concrete classes. An object is called an instance of its class. An abstract class cannot be instantiated.

  5. Different concrete classes in the same hierarchy may define the same method in different ways. For example:

    public class Fish extends SeaCreature{
      ...

      /**
       * Returns the name of the creature
       */
      public String getName(){
        return "Wanda the Fish";
      }
      ...
    }

    public class Mermaid extends SeaCreature{
      ...

      /**
       * Returns the name of the creature
       */
      public String getName(){
        return "Ariel the Mermaid";
      }
      ...
    }

 

Main Previous Next
Contact
 © ICT 2006, All Rights Reserved.